"""
/* Copyright 2018 The Enflame Tech Company. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
"""
# !/usr/bin/python
# coding=utf-8

import subprocess
import traceback
import socket
from collections import OrderedDict


class HostInfo(object):
    def __init__(self):
        self.dict = OrderedDict([('total_mem', "{}MB".format(self.get_host_mem())),
                                 ('cpu_model_name', self.get_host_model()),
                                 ('cpu_cores', self.get_host_cores()),
                                 ('host_name', self.get_host_name()),
                                 ('test_host_ip', self.get_local_ip())])

    def get_local_ip(self):
        try:
            proc = subprocess.Popen(["ip -o -4 route show to default | awk '{print $5}'"], stdout=subprocess.PIPE,
                                    shell=True)
            iface_name = proc.communicate()[0].strip()
            iface_name = iface_name.decode('utf-8')
            # if many iface name, only get first
            iface_name = iface_name.split("\n")[0]
            proc = subprocess.Popen(["ip -4 addr show {} | awk '/inet/ {{print $2}}' | cut -d/ -f1".format(iface_name)],
                                    stdout=subprocess.PIPE, shell=True)
            node_ip = proc.communicate()[0].strip()
            local_ip = node_ip.decode('utf-8').split("\n")[0]
        except Exception as ex:
            local_ip = "unknown_ip"
        return str(local_ip.strip())

    def get_host_mem(self):
        try:
            proc = subprocess.Popen(["free -m |grep Mem |awk -F\" \" '{print $2}'"],
                                    stdout=subprocess.PIPE, shell=True)
            host_mem = proc.communicate()[0].strip()
            host_mem = host_mem.decode('utf-8').split("\n")[0]
        except Exception as ex:
            host_mem = ""
            traceback.print_exc()
        return str(host_mem.strip())

    def get_host_model(self):
        try:
            proc = subprocess.Popen(["cat /proc/cpuinfo |grep \"model name\" |uniq |awk -F\":\" '{print $2}'"],
                                    stdout=subprocess.PIPE, shell=True)
            cpu_model = proc.communicate()[0].strip()
            cpu_model = cpu_model.decode('utf-8').split("\n")[0]
        except Exception as ex:
            cpu_model = ""
            traceback.print_exc()
        return str(cpu_model.strip())

    def get_host_name(self):
        try:
            host_name = socket.gethostname()
        except Exception as ex:
            host_name = ""
            traceback.print_exc()
        return str(host_name.strip())

    def get_host_cores(self):
        try:
            proc = subprocess.Popen(["cat /proc/cpuinfo |grep \"cpu cores\" |uniq |awk -F\":\" '{print $2}'"],
                                    stdout=subprocess.PIPE, shell=True)
            cpu_cores = proc.communicate()[0].strip()
            cpu_cores = cpu_cores.decode('utf-8').split("\n")[0]
        except Exception as ex:
            cpu_cores = ""
            traceback.print_exc()
        return 14


if __name__ == '__main__':
    host_info = HostInfo().dict
    print(host_info)
